<?php
namespace Admin\Controller;

class CommonController extends AdminController{
	
	/**
	 * 添加操作
	 */
	public function addCommon(){
		$m = M(I('post.table'));
        $methods = I('post.methods');
		$fields = explode(';', I('post.fields'));	//获取所需字段信息
        //带参数
        $params = I('post.params', '');
        $where = array();
        if($params != ''){
            $temp_params = explode(';', $params);
            foreach($temp_params as $tv){
                $tvrow = explode(',', $tv);
                $where = array("{$tvrow[0]}" => $tvrow[1]);
            }
        }
		$data = array();
        $ctime = 0;
        $field_time = '';
		foreach ($fields as $key => $v){
			$row = explode(',', $v);

            switch($row[1]){
                case 'text':
                    $data[$row[0]] = I('post.' .$row[0]);
                    break;
                case 'text-date':
                    $data[$row[0]] = time();
                    braak;
                case 'array_string':
                    $list = I('post.' .$row[0]);
                    foreach ($list as $key => $v){
                        $data[$row[0]] .= $key == 0 ? $v : ',' . $v;
                    }
                    break;
                case 'date':
                    $ctime = time();
                    $field_time = $row[0];
                    break;
            }
		}
		$id = I('post.id');
		if($id > 0){
            $m->create($data);
			if($m->where(array('id' => $id))->save($data)){
                if($methods == 'current'){
                    $this->success('修改成功！');
                }else{
                    if(!empty($where)){
                        $this->success('修改成功！', U("$methods/index", $where));
                    }else{
                        $this->success('修改成功！', U("$methods/index"));
                    }
                }
			}else{
                $this->error('修改失败，请检查重试！');
			}	
		}else{
            if($ctime > 0){
                $data[$field_time] = $ctime;
            }
            $m->create($data);
			if($m->add()){
                if($methods == 'current') {
                    $this->success('添加成功！');
                }else{
                    if(!empty($where)){
                        $this->success('添加成功！', U("$methods/index", $where));
                    }else{
                        $this->success('添加成功！', U("$methods/index"));
                    }
                }
			}else{
                $this->error('添加失败，请检查是否有字段写入错误！');
			}
		}
	}
	
	/**
	 * 删除操作
	 */
	public function delCommon(){
		$m = M(I('get.table'));
		$id = I('get.id');
		if($m->where(array('id' => $id))->delete()){
            $this->success('删除成功！');
		}else{
            $this->error('删除失败，请稍后再试！');
		}
	}
	
}